<template>
	<view>
		<page-container></page-container>
	</view>
</template>
<script>
	import indexApi from "@/apis/apiList/indexApi.js"
	import liveApi from "@/apis/apiList/liveApi.js"
	import TencentCloudChat from '@tencentcloud/chat'
	import {
		tim,
		initTIM,
		addMessageListener,
		removeMessageListener
	} from "@/apis/IM.js"

	export default {
		onLaunch: function() {
			uni.$on('send-msg', this.sendMsg)

			// console.warn('当前组件仅支持 uni_modules 目录结构 ，请升级 HBuilderX 到 3.1.0 版本以上！')
			console.log('App Launch')
			// 获取用户签名
			if (uni.getStorageSync('user')) {
				liveApi.membergetLiveTokens({
					id: `${uni.getStorageSync('user').id}`
				}).then(res => {
					// 初始化腾讯云IM
					this.initTencentIM(res.data.code);
				})
			}
			// 查询字典
			indexApi.getSystruthList().then(res => {
				uni.setStorageSync('dict', res.data)
			})
			const systemInfo = uni.getSystemInfoSync();
			if (systemInfo.system.indexOf('Android') !== -1) {
				getApp().globalData.appTop = `${uni.getSystemInfoSync().statusBarHeight}px`
				plus.device.setWakelock(true) //屏幕常量
			}
			const addparmeList = [{
				text: "难以入睡",
				value: "难以入睡"
			}, {
				text: "冲动易怒",
				value: "冲动易怒"
			}, {
				text: "胡思乱想",
				value: "胡思乱想"
			}, {
				text: "伤害自己",
				value: "伤害自己"
			}, {
				text: "食欲不振",
				value: "食欲不振"
			}, {
				text: "周身酸痛",
				value: "周身酸痛"
			}, {
				text: "无法沟通",
				value: "无法沟通"
			}, {
				text: "恐惧社交",
				value: "恐惧社交"
			}, {
				text: "全身无力",
				value: "全身无力"
			}, {
				text: "迷惘无助",
				value: "迷惘无助"
			}, {
				text: "逐渐消瘦",
				value: "逐渐消瘦"
			}, {
				text: "暴饮暴食",
				value: "暴饮暴食"
			}, ]
			if (!uni.getStorageSync('addparme')) {
				uni.setStorageSync('addparme', addparmeList)
			}
		},
		onShow: function() {
			console.log('App Show')

		},
		onHide: function() {
			console.log('App Hide')
			uni.$off('send-msg')
		},
		methods: {
			sendMsg(fromAccount, payload) {
				console.log(fromAccount, payload);
				const message = tim.createCustomMessage({
					to: fromAccount,
					conversationType: TencentCloudChat.TYPES.CONV_C2C,
					payload: payload,
				});
				tim.sendMessage(message);
			},
			async initTencentIM(userSig) {
				try {
					// 替换为你的腾讯云IM配置
					const options = {
						SDKAppID: 1400752704, // 你的应用SDKAppID
						userID: `${uni.getStorageSync('user').id}`, // 当前用户ID
						userSig: userSig // 当前用户签名
					};
					uni.setStorageSync('txOption', options)
					// 初始化TIM
					await initTIM(options);

					// 添加全局消息监听
					this.messageListener = (event, data) => {
						// 根据事件类型处理不同消息
						switch (event) {
							case 'MESSAGE_RECEIVED':
								this.handleNewMessage(data);
								break;
							case 'MESSAGE_REVOKED':
								this.handleRevokedMessage(data);
								break;
							case 'CONVERSATION_UPDATED':
								this.handleConversationUpdate(data);
								break;
							case 'KICKED_OUT':
								this.handleKickedOut(data);
								break;
							case 'SDK_NOT_READY':
								tim.login()
								break;

								// 其他事件处理...
						}
					};

					addMessageListener(this.messageListener);
					getApp().globalData.tim = tim
				} catch (error) {
					uni.showToast({
						title: '初始化腾讯云IM失败'
					})
					console.error('初始化腾讯云IM失败:', error);
				}
			},

			// 处理新消息
			handleNewMessage(messages) {
				// messages 是消息数组
				messages.forEach(message => {
					console.log('处理新消息:', message);
					const msg = message.payload
					if (msg.data == 'phone') {
						const {
							nickname,
							headimg
						} = JSON.parse(msg.extension)
						uni.redirectTo({
							url: `/pages/views/makePhone?type=receive&fromAccount=${msg.description}&info=${JSON.stringify({name:nickname,headimg:headimg})}`
						})
					}
					if (msg.data == 'unPhone') {
						uni.reLaunch({
							url: '/pages/tabbar/msg'
						})
					}
					if (msg.data == 'privateChat') this.privateChat(msg.description, '')
				});
			},
			privateChat(anchorId, id) {
				uni.redirectTo({
					url: `/pages/msg/privateChat?anchorId=${anchorId}&id=${id}`
				})
			},
			// 处理撤回消息
			handleRevokedMessage(messages) {
				messages.forEach(message => {
					console.log('消息被撤回:', message);
					// 处理消息撤回逻辑
				});
			},

			// 处理会话更新
			handleConversationUpdate(conversations) {
				console.log('会话更新:', conversations);
				uni.showToast({
					icon: 'none',
					title: '会话更新'
				})
				// 处理会话更新逻辑
			},

			// 处理被踢下线
			handleKickedOut(data) {
				console.log('被踢下线:', data);
				// uni.showModal({
				// 	title: '提示',
				// 	content: '您的账号在其他设备登录，已被踢下线',
				// 	showCancel: false,
				// 	success: () => {
				// 		// 跳转到登录页或其他处理
				// 	}
				// });
			}
		},

		beforeDestroy() {
			// 移除消息监听
			if (this.messageListener) {
				removeMessageListener(this.messageListener);
			}
		}
	}
</script>
<style lang="scss">
	/*每个页面公共css */
	@import '@/uni_modules/uni-scss/index.scss';
	@import '@/static/customicons.css';
	@import '@/static/tailwind.css';
	@import '@/static/common.css';

	// 设置整个项目的背景色
	page {
		--x-font-size-xs: 24rpx;
		--x-font-size-sm: 28rpx;
		--x-font-size-md: 32rpx;
		--x-font-size-lg: 36rpx;
		// background-color: #f5f5f5;
		background-image: url("/static/test/bg.png");
		background-size: contain;
		background-color: #F3FAFF;
		background-repeat: no-repeat;
		font-size: 24rpx;
	}

	view {
		box-sizing: border-box;
	}
</style>